import React from 'react'
import PropTypes from 'prop-types'
import jquery from 'jquery'
import { Form, Input, Modal, Select, message, Upload, Button, Icon } from 'antd'
import fetch from 'utils/fetch'

import config from 'utils/config'

const { ajax } = jquery
const { api } = config
const { targetHost } = api

const FormItem = Form.Item

const formItemLayout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
}

const modal = ({
  item = {},
  file,
  onOk,
  dispatch,
  form: {
    getFieldDecorator,
    validateFields,
    getFieldsValue,
  },
  ...modalProps
}) => {
  const handleOk = () => {
    validateFields((errors) => {
      if (errors) {
        return
      }
      const data = {
        ...getFieldsValue(),
      }
      if (item.type === '1' && file.length === 0) {
        message.error('请上传文件')
        return
      }
      if (item.type === '1' && file[0].status !== 'done') {
        message.error('请等待文件上传完成')
        return
      }
      onOk({ content: item.type === '1' ? file[0].name : JSON.stringify(data) })
    })
  }

  const modalOpts = {
    ...modalProps,
    onOk: handleOk,
  }

  const props = {
    fileList: file,
    customRequest: (fileItem) => {
      setTimeout(function() {
        const form = new FormData()
        form.append('file', fileItem.file)
        fetch.upload('/common/upload', form).then((res) => {
          const { success, data, errorMsg } = res
          if (success) {
            if (file.length > 0) {
              file[0].name = data
              file[0].status = 'done'
              dispatch({
                type: 'project/updateState',
                payload: {
                  file,
                },
              })
            }
          } else {
            message.fail('文件上传失败')
          }
        })
      }, 3000)
    },
    beforeUpload: function(file) {
      if (file.size > 10 * 1024 * 1024) {
        message.error('文件尺寸不得超过10M')
        return false
      }
      return true
    },
    onChange: function(data) {
      if (data.file.status === 'uploading') {
        dispatch({
          type: 'project/updateState',
          payload: {
            file: [data.file],
          },
        })
      }
    },
    onRemove: function(data) {
      dispatch({
        type: 'project/updateState',
        payload: {
          file: [],
        },
      })
    }
  }

  return (
    <Modal {...modalOpts}>
      <Form layout="horizontal">
        <FormItem label="主题" hasFeedback {...formItemLayout}>
          {item.name}
        </FormItem>
        <FormItem label="项目类型" hasFeedback {...formItemLayout}>
          {item.type === '0' ? '数据协同' : '文件协同'}
        </FormItem>
        <FormItem label="项目说明" hasFeedback {...formItemLayout}>
          {item.description}
        </FormItem>
        {item.type === '0' && item.fields.map((d) => {
          return (
            <FormItem key={d.id} label={d.name} hasFeedback {...formItemLayout}>
              {getFieldDecorator(`${d.id}`, {
                initialValue: item.content ? JSON.parse(item.content)[d.id] : '',
                rules: [
                  {
                    required: true,
                  },
                ],
              })(<Input type="text" placeholder={d.description} />)}
            </FormItem>
          )
        })}
        {item.type === '1' && <FormItem label="文件上传" hasFeedback {...formItemLayout}>
          {getFieldDecorator('file', {
            initialValue: item.content,
            rules: [
              {
                required: true,
              },
            ],
          })(<Upload {...props}>
            <Button>
              <Icon type="upload" /> 文件上传
            </Button>
          </Upload>)}
        </FormItem>}
        {item.type === '1' && item.content && <FormItem label="已上传文件" hasFeedback {...formItemLayout}>
          {item.content}
          </FormItem>}
      </Form>
    </Modal>
  )
}

modal.propTypes = {
  form: PropTypes.object.isRequired,
  type: PropTypes.string,
  item: PropTypes.object,
  dispatch: PropTypes.func,
  file: PropTypes.array,
  onOk: PropTypes.func,
}

export default Form.create()(modal)
